package top.system.dept.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.system.dept.mapper.ItemMapper;
import top.system.dept.pojo.Item;
import top.system.dept.pojo.SysResp;
import top.system.dept.pojo.User;
import top.system.dept.utils.ConstantPool;
import top.system.dept.utils.RespUtil;
import top.system.dept.utils.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: ItemService
 * @Author: Amosen
 * @Since: 2021/5/19
 */

@Service
public class ItemService {

    Logger logger = LoggerFactory.getLogger(ItemService.class);

    @Autowired
    UserService userService;

    @Autowired
    WechatService wechatService;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Value("${data.page.size}")
    private Integer defaultPageSize;

    @Value("${data.page.num}")
    private Integer defaultPageNum;

    @Value("${mini.item.add.check.orderId.prefix}")
    private String orderIdPrefix;

    @Value("${mini.item.add.check.orderId.suffix}")
    private String orderIdSuffix;

    @Value("${mini.item.add.check.notify.id}")
    private String addingItemNotifyId;

    @Value("${mini.item.add.check.page}")
    private String checkPage;

    @Value("${mini.item.add.check.notify.checkType.key}")
    private String checkTypeKey;

    @Value("${mini.item.add.check.notify.orderId.key}")
    private String orderIdKey;

    @Value("${mini.item.add.check.notify.time.key}")
    private String timeKey;

    @Value("${mini.item.add.check.notify.checkThing.key}")
    private String checkThingKey;

    @Value("${mini.item.add.check.notify.applyUser.key}")
    private String applyUserKey;

    @Value("${item.save.img.prefix}")
    private String saveImgPrefix;

    @Value("${item.save.img.path}")
    private String saveImgPath;

    private static final String INSERT_ADDING_ITEM = "INSERT into `addingItem` (" +
            "`orderid`, `name`, `itemPic`, `number`, `status`" +
            ") values (?, ?, ?, ?, ?);";

    private static final String SUBMITTED = "已提交";

    private static final String CHECKING = "审核中";

    private static final String NO_PASS = "未通过";

    private static final String addItemCheckType = "添加仓储物资审核";

    public SysResp handleAddItem(String userModal, String itemName, Integer itemNumber, MultipartFile itemPic, HttpServletRequest request) {
        User user = userService.getUserByModal(userModal);
        if (user == null) {
            return RespUtil.noLogin();
        }
        if (!userService.canUseRoot(userModal)) {
            return RespUtil.lowAuth();
        }

        if ((!StringUtils.hasText(itemName)) || itemNumber == null || itemPic.isEmpty()) {
            return RespUtil.illegalParam();
        }

        // 生成新的文件名
        String originalFilename = itemPic.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        String fileName = saveImgPrefix + System.currentTimeMillis() + suffix;

        // 本地保存路径
//        String serverPath = System.getProperty("user.dir") + File.separator + saveImgPath;
        String serverPath = request.getServletContext().getRealPath("") + saveImgPath;
        File dir = new File(serverPath);
        if ((!dir.isDirectory()) || (!dir.exists())) {
            dir.mkdirs();
        }
        File destFile = new File(serverPath, fileName);
        try {
            itemPic.transferTo(destFile);
        } catch (IOException e) {
            return RespUtil.fail();
        }

        // 网络访问路径
        String netPath = request.getScheme() + "://" +
                request.getServerName() + ":" + request.getLocalPort() + saveImgPath + fileName;

        Item item = new Item(null, itemName, itemNumber, user.getDept().getId(), netPath);
        int i = itemMapper.addItem(item);
        if (i > 0) {
            return RespUtil.success();
        } else {
            destFile.delete();
            return RespUtil.fail();
        }
    }

    public SysResp getItems(Integer pageNum, Integer pageSize) {
        if (pageSize == null) {
            pageSize = defaultPageSize;
        }
        if (pageNum == null) {
            pageNum = defaultPageNum;
        }
        List<Item> items = itemMapper.getItem(pageNum * pageSize, pageSize);
        return RespUtil.successData("items", items);
    }

    public SysResp updateItem(String userModal, Item item) {
        boolean b = userService.canUseRoot(userModal);
        if (!b) {
            return RespUtil.fail();
        } else {
            Item savedItem = itemMapper.getItemById(item.getId());
            if (savedItem == null) {
                return RespUtil.fail();
            } else {
                savedItem.setName(item.getName());
                savedItem.setNumber(item.getNumber());
                int i = itemMapper.updateItem(savedItem);
                return i > 0 ? RespUtil.success() : RespUtil.fail();
            }

        }
    }

    public int countItem() {
        return itemMapper.countItem();
    }

}
